<template>
  <div>
    <span id="qqLoginBtn" v-show="false"></span>
    <z-svg-icon
      name="qq"
      class="w-4 h-4 cursor-pointer"
      @click="onQQLogin"
    ></z-svg-icon>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import brodacast from './brodacast'
import { oauthLogin } from './oauth'
import { LOGIN_TYPE } from '@/constants/index'

// QQ 登录的 URL
const QQ_LOGIN_URL =
  'https://graph.qq.com/oauth2.0/authorize?client_id=102793638&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fzylucky.top%2Flogin'

// QQ登录挂起
// QQ登录存在缓存，登陆成功一次后，后续会自动登录
onMounted(() => {
  QC.Login(
    {
      btnId: 'qqLoginBtn' // 按钮id
    },
    (data, opts) => {
      console.log('QQ登录成功')
      // 注销登录，防止缓存
      QC.Login.signOut()
      const accessToken = /access_token=((.*))&expires_in/.exec(
        window.location.hash
      )[1]
      // 拼接获取到的数据对象
      const oauthObj = {
        pickname,
        figureurl_qq_2,
        accessToken
      }
      // 通过广播将数据发送给父组件
      brodacast.send(oauthObj)
      // 移动端没有窗口概念，直接进行后续操作
      oauthLogin(LOGIN_TYPE.QQ, oauthobj)
      // 关闭当前窗口
      window.close()
    }
  )
})

/**
 * QQ登录
 */
const onQQLogin = () => {
  openQQWindow()
}

/**
 * QQ登录弹窗
 */
const openQQWindow = () => {
  window.open(
    QQ_LOGIN_URL,
    'oauth2Login_10609',
    'height=525,width=585, toolbar=no, menubar=no, scrollbars=no, status=no, location=yes, resizable=yes'
  )
  // 等待
  brodacast.wait().then((oauthobj) => {
    brodacast.clear()
    // 处理登录成功后的逻辑
    oauthLogin(LOGIN_TYPE.QQ, oauthobj)
  })
}
</script>

<style lang="scss" scoped></style>
